package com.btpj.blog_server.controller.admin;

import com.btpj.blog_server.entity.BaseResp;
import com.btpj.blog_server.entity.Role;
import com.btpj.blog_server.entity.User;
import com.btpj.blog_server.service.UserService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class UserManagerController {

    @Autowired
    UserService userService;

    @GetMapping("/users")
    public BaseResp<List<User>> getUsersByNickName(String nickName) {
        List<User> users = userService.getUsersByNickName(nickName);
        return new BaseResp<>(0, "请求成功", users);
    }

    @GetMapping("/allRoles")
    public BaseResp<List<Role>> getAllRoles() {
        return new BaseResp<>(0, "请求成功", userService.getAllRoles());
    }

    @PutMapping("/user/updateRoles")
    public BaseResp<String> updateUserRoles(Long[] roleIds, Long userId) {
        if (roleIds.length == 0) {
            return new BaseResp<>(1, "用户必须拥有至少一个角色");
        }
        if (userService.updateUserRoles(roleIds, userId) == roleIds.length) {
            return new BaseResp<>(0, "更新成功");
        } else {
            return new BaseResp<>(0, "更新失败");
        }
    }

    @PutMapping("/user/enable")
    public BaseResp<String> setUserEnable(Boolean enable, Long userId) {
        if (userService.setUserEnable(enable, userId) == 1) {
            return new BaseResp<>(0, enable ? "启用成功" : "禁用成功");
        } else {
            return new BaseResp<>(1, enable ? "启用失败" : "禁用失败");
        }
    }

    @DeleteMapping("/user/deleteUserById")
    public BaseResp<String> deleteUserById(Long userId) {
        if (userService.deleteUserById(userId) == 1) {
            return new BaseResp<>(0, "删除用户成功");
        } else {
            return new BaseResp<>(1, "删除用户失败");
        }
    }
}
